// 交互反馈组合式函数
// 提供触觉反馈和音效支持

import { ref, onMounted } from 'vue'

export function useInteractionFeedback() {
  const isVibrationSupported = ref(false)
  const isSoundEnabled = ref(true)
  
  // 检测触觉反馈支持
  onMounted(() => {
    isVibrationSupported.value = 'vibrate' in navigator
  })
  
  /**
   * 触发触觉反馈
   * @param {string} type - 反馈类型: 'light', 'medium', 'heavy'
   */
  const vibrate = (type = 'light') => {
    if (!isVibrationSupported.value) return
    
    const patterns = {
      light: 10,      // 轻触
      medium: 20,     // 中等
      heavy: 30,      // 重触
      success: [10, 50, 10],  // 成功
      error: [50, 100, 50]    // 错误
    }
    
    try {
      navigator.vibrate(patterns[type] || patterns.light)
    } catch (error) {
      console.warn('Vibration failed:', error)
    }
  }
  
  /**
   * 播放交互音效
   * @param {string} type - 音效类型
   */
  const playSound = (type = 'click') => {
    if (!isSoundEnabled.value) return
    
    // 使用 Web Audio API 生成简单音效
    try {
      const audioContext = new (window.AudioContext || window.webkitAudioContext)()
      const oscillator = audioContext.createOscillator()
      const gainNode = audioContext.createGain()
      
      oscillator.connect(gainNode)
      gainNode.connect(audioContext.destination)
      
      // 根据类型设置不同的音效参数
      const soundParams = {
        click: { frequency: 800, duration: 50, volume: 0.1 },
        hover: { frequency: 600, duration: 30, volume: 0.05 },
        success: { frequency: 1000, duration: 100, volume: 0.15 },
        error: { frequency: 400, duration: 150, volume: 0.15 }
      }
      
      const params = soundParams[type] || soundParams.click
      
      oscillator.frequency.value = params.frequency
      oscillator.type = 'sine'
      
      gainNode.gain.setValueAtTime(params.volume, audioContext.currentTime)
      gainNode.gain.exponentialRampToValueAtTime(
        0.01, 
        audioContext.currentTime + params.duration / 1000
      )
      
      oscillator.start(audioContext.currentTime)
      oscillator.stop(audioContext.currentTime + params.duration / 1000)
    } catch (error) {
      console.warn('Sound playback failed:', error)
    }
  }
  
  /**
   * 综合交互反馈
   * @param {string} type - 交互类型
   * @param {object} options - 选项 { vibrate: true, sound: true }
   */
  const feedback = (type = 'click', options = {}) => {
    const { vibrate: enableVibrate = true, sound: enableSound = false } = options
    
    if (enableVibrate) {
      vibrate(type)
    }
    
    if (enableSound) {
      playSound(type)
    }
  }
  
  /**
   * 切换音效开关
   */
  const toggleSound = () => {
    isSoundEnabled.value = !isSoundEnabled.value
    return isSoundEnabled.value
  }
  
  return {
    isVibrationSupported,
    isSoundEnabled,
    vibrate,
    playSound,
    feedback,
    toggleSound
  }
}


